/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.rate.file.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import lombok.extern.slf4j.Slf4j;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.springblade.modules.rate.file.entity.FileDocument;
import org.springblade.modules.rate.file.vo.FileDocumentVO;
import org.springblade.modules.rate.file.service.IFileDocumentService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件文档管理 控制器
 *
 * @author Blade
 * @since 2021-09-24
 */
@RestController
@RequestMapping("rate/file/filedocument")
@Api(value = "文件文档管理", tags = "文件文档管理接口")
@Slf4j
public class FileDocumentController extends BladeController {

	@Autowired
	private IFileDocumentService fileDocumentService;

	/**
	 * 图片保存路径，自动从yml文件中获取数据
	 *   示例： E:/images/
	 */
	@Value("${file-save-path}")
	private String fileSavePath;

	@Value("${file-save-host:http://rate.cmaker.cn/}")
	private String fileSaveHost;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入fileDocument")
	public R<FileDocument> detail(FileDocument fileDocument) {
		FileDocument detail = fileDocumentService.getOne(Condition.getQueryWrapper(fileDocument));
		return R.data(detail);
	}

	/**
	 * 分页 文件文档管理
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入fileDocument")
	public R<IPage<FileDocument>> list(FileDocument fileDocument, Query query) {
		IPage<FileDocument> pages = fileDocumentService.page(Condition.getPage(query), Condition.getQueryWrapper(fileDocument));
		return R.data(pages);
	}

	/**
	 * 自定义分页 文件文档管理
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入fileDocument")
	public R<IPage<FileDocumentVO>> page(FileDocumentVO fileDocument, Query query) {
		IPage<FileDocumentVO> pages = fileDocumentService.selectFileDocumentPage(Condition.getPage(query), fileDocument);
		return R.data(pages);
	}

	/**
	 * 新增 文件文档管理
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入fileDocument")
	public R save(@Valid @RequestBody FileDocument fileDocument) {
		return R.status(fileDocumentService.save(fileDocument));
	}

	/**
	 * 修改 文件文档管理
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入fileDocument")
	public R update(@Valid @RequestBody FileDocument fileDocument) {
		return R.status(fileDocumentService.updateById(fileDocument));
	}

	/**
	 * 新增或修改 文件文档管理
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入fileDocument")
	public R submit(@Valid @RequestBody FileDocument fileDocument) {
		return R.status(fileDocumentService.saveOrUpdate(fileDocument));
	}


	/**
	 * 删除 文件文档管理
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(fileDocumentService.removeByIds(Func.toLongList(ids)));
	}

	    /**
     * 数组 代码自定义代号
     */
    @GetMapping("/item")
    @ApiOperationSupport(order = 10)
    @ApiOperation(value = "数组", notes = "传入fileDocument")
    public R<List<FileDocument>> list(FileDocument fileDocument) {
        List<FileDocument> items = fileDocumentService.list(Condition.getQueryWrapper(fileDocument));
        return R.data(items);
    }

	/**
	 * 上次图片
	 */
	@PostMapping(path = "/upload")
	public R uploadFile(MultipartFile file,
						HttpServletRequest request) {


		//1.后半段目录：  2020/03/15
		String dateStr = DateUtil.format(new Date(),"yyyyMMddHHmmss");
		/**
		 *  2.文件保存目录  E:/images/2020/03/15/
		 *  如果目录不存在，则创建
		 */
		String path = fileSavePath;
		log.info("图片上传，保存位置：" + path);
		//3.给文件重新设置一个名字
		//后缀
		String newFileName= file.getOriginalFilename();
		//4.创建这个新文件
		File newFile = new File(path + '/' + newFileName);
		if (!newFile.exists()) {
			newFileName = dateStr + file.getOriginalFilename();
			newFile = new File(path + '/' + newFileName);
		}
		//5.复制操作
		try {
			file.transferTo(newFile);
			//协议 :// ip地址 ：端口号 / 文件目录(/images/2020/03/15/xxx.jpg)
			String url = fileSaveHost  + '/'  +  newFileName;
			this.exec777(newFileName);
			FileDocument document = new FileDocument();
			document.setMediaUrl(url);
			fileDocumentService.save(document);
			return R.data(document);
		} catch (IOException e) {
			log.error("保存失败,{}",e.getMessage());
			throw new ServiceException("保存失败 " + e.getMessage());
		}
	}

	private void exec777(String path) {
		try {
			//判断是否为linux系统
			if(System.getProperty("os.name").toLowerCase().contains("linux")) {
				Runtime.getRuntime().exec("chmod 777 " +path);
			}
		} catch (IOException e) {
			System.out.println("为"+path+"赋予777权限时出现异常");
		}
	}



}
